<!--
  * 菜单列表
  *
  * @Author:    zhoujk
  * @Date:      2025-02-05 16:10
-->
<template>
  <div>
    <a-form class="smart-query-form">
      <a-row class="smart-query-form-row">
        <a-form-item label="用户类型" class="smart-query-form-item">
          <a-radio-group v-model:value="queryForm.userType" button-style="solid" @change="query">
            <a-radio-button v-for="item in ZZB_USER_TYPE_ENUM" :key="item.value" :value="item.value">
              {{ item.desc }}
            </a-radio-button>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="关键字" class="smart-query-form-item">
          <a-input style="width: 300px" v-model:value="queryForm.keywords" placeholder="菜单名称/路由地址/组件路径/权限字符串" />
        </a-form-item>

        <a-form-item label="类型" class="smart-query-form-item">
          <SmartEnumSelect width="120px" v-model:value="queryForm.type" placeholder="请选择类型" enum-name="ZZB_MENU_TYPE_ENUM" />
        </a-form-item>

        <a-form-item label="状态" class="smart-query-form-item">
          <SmartEnumSelect width="120px" enum-name="ZZB_ENABLE_STATUS_ENUM" v-model:value="queryForm.status" />
        </a-form-item>

        <a-form-item class="smart-query-form-item smart-margin-left10">
          <a-button-group>
            <a-button type="primary" @click="query">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>

            <a-button @click="resetQuery">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-button-group>
        </a-form-item>
      </a-row>
    </a-form>

    <a-card size="small" :bordered="false" :hoverable="true">
      <a-row class="smart-table-btn-block">
        <div class="smart-table-operate-block">
          <a-button v-privilege="'menu:insert'" type="primary" @click="showDrawer">
            <template #icon>
              <PlusOutlined />
            </template>
            添加菜单
          </a-button>

          <!--          <a-button v-privilege="'system:menu:batchDelete'" type="primary" danger @click="batchDelete" :disabled="!hasSelected">-->
          <!--            <template #icon>-->
          <!--              <DeleteOutlined />-->
          <!--            </template>-->
          <!--            批量删除-->
          <!--          </a-button>-->
        </div>
        <div class="smart-table-setting-block">
          <!-- <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.SYSTEM.MENU" :refresh="query" /> -->
        </div>
      </a-row>

      <a-table
        size="small"
        :defaultExpandAllRows="true"
        :dataSource="tableData"
        bordered
        :columns="columns"
        :loading="tableLoading"
        rowKey="id"
        :pagination="false"
        :scroll="{ x: 1200, y: 600 }"
      >
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'type'">
            <a-tag :color="menuTypeColorArray[text]">{{ $smartEnumPlugin.getDescByValue('ZZB_MENU_TYPE_ENUM', text) }} </a-tag>
          </template>

          <template v-if="column.dataIndex === 'component'">
            <span>{{ record.component }}</span>
          </template>

          <template v-if="column.dataIndex === 'status'">
            <a-switch
              v-privilege="'menu:update_status'"
              :checked="text === ZZB_ENABLE_STATUS_ENUM.ENABLE_STATUS.value"
              @change="(checked) => handleStatusChangeConfirm(checked, record)"
              :loading="record.statusLoading"
            />
          </template>

          <template v-if="column.dataIndex === 'icon'">
            <component :is="$antIcons[text]" />
          </template>

          <template v-if="column.dataIndex === 'operate'">
            <div class="smart-table-operate">
              <a-button v-if="!record.status" v-privilege="'menu:update'" type="link" size="small" @click="showDrawer(record)">编辑 </a-button>
              <a-button v-if="!record.status" v-privilege="'menu:delete'" danger type="link" @click="singleDelete(record)">删除 </a-button>
            </div>
          </template>
        </template>
      </a-table>
    </a-card>

    <MenuOperateModal ref="menuOperateModal" @reloadList="query" />
  </div>
</template>
<script setup>
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
  import { message, Modal } from 'ant-design-vue'
  import { createVNode, onMounted, reactive, provide, ref, toRef } from 'vue'
  import MenuOperateModal from './components/menu-operate-modal.vue'
  import { buildMenuTableTree, filterMenuByQueryForm } from './menu-data-handler.js'
  import { columns } from './menu-list-table-columns.js'
  import { menuApi } from '/src/api/system/b-operation/menu-api'
  import { menuMerchantApi } from '/src/api/system/b-merchant/menu-api'
  import SmartEnumSelect from '/src/components/framework/smart-enum-select/index.vue'
  import { SmartLoading } from '/src/components/framework/smart-loading'
  import { smartSentry } from '/src/lib/smart-sentry'
  import TableOperator from '/src/components/support/table-operator/index.vue'
  import { TABLE_ID_CONST } from '/src/constants/support/table-id-const'
  import { ZZB_ENABLE_STATUS_ENUM, ZZB_USER_TYPE_ENUM } from '/src/constants/system/system-const.js'

  // ------------------------ 表格渲染 ------------------------
  const menuTypeColorArray = ['red', 'blue', 'orange', 'green']

  // ------------------------ 查询表单 ------------------------

  const queryFormState = {
    userType: ZZB_USER_TYPE_ENUM.USER_TYPE_PLATFORM.value,
    keywords: '',
    type: undefined,
    frameFlag: undefined,
    cacheFlag: undefined,
    visibleFlag: undefined,
    status: undefined,
  }
  const queryForm = reactive({ ...queryFormState })

  // ------------------------ table表格数据和查询方法 ------------------------

  const tableLoading = ref(false)
  const tableData = ref([])

  function resetQuery() {
    Object.assign(queryForm, queryFormState)
    query()
  }

  onMounted(query)

  async function query() {
    try {
      tableLoading.value = true
      let responseModel
      if (ZZB_USER_TYPE_ENUM.USER_TYPE_MERCHANT.value === selectedUserType.value) {
        responseModel = await menuMerchantApi.list({ userType: queryForm.userType })
      } else {
        responseModel = await menuApi.list({ userType: queryForm.userType })
      }
      // 过滤搜索条件
      const filtedMenuList = filterMenuByQueryForm(responseModel.data, queryForm)
      // 递归构造树形结构，并付给 TableTree组件
      tableData.value = buildMenuTableTree(filtedMenuList.sort((a, b) => a.num - b.num))
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      tableLoading.value = false
    }
  }

  function singleDelete(record) {
    Modal.confirm({
      title: '确定要删除如下菜单吗?',
      icon: createVNode(ExclamationCircleOutlined),
      content: record.name,
      okText: '删除',
      okType: 'danger',
      onOk() {
        requestBatchDelete(record.id)
      },
      cancelText: '取消',
      onCancel() {},
    })

    async function requestBatchDelete(menuId) {
      SmartLoading.show()
      try {
        if (ZZB_USER_TYPE_ENUM.USER_TYPE_MERCHANT.value === selectedUserType.value) {
          await menuMerchantApi.delete({ id: menuId })
        } else {
          await menuApi.delete({ id: menuId })
        }
        message.success('删除成功!')
        query()
      } catch (e) {
        smartSentry.captureError(e)
      } finally {
        SmartLoading.hide()
      }
    }
  }

  // ---------------------------- 状态修改 ----------------------------
  const handleStatusChangeConfirm = async (checked, record) => {
    Modal.confirm({
      title: '状态变更',
      icon: createVNode(ExclamationCircleOutlined),
      content: `确认修改"${record.name}"状态为${checked ? '启用' : '禁用'}`,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        handleStatusChange(checked, record)
      },
    })
  }

  const handleStatusChange = async (checked, record) => {
    // 保存原始值用于错误回滚
    const originalStatus = record.status
    // 将布尔值转换为 0/1
    const targetStatus = checked ? ZZB_ENABLE_STATUS_ENUM.ENABLE_STATUS.value : ZZB_ENABLE_STATUS_ENUM.DISABLE_STATUS.value
    try {
      record.statusLoading = true
      let response
      if (ZZB_USER_TYPE_ENUM.USER_TYPE_MERCHANT.value === selectedUserType.value) {
        response = await menuMerchantApi.updateStatus({ id: record.id, status: targetStatus })
      } else {
        response = await menuApi.updateStatus({ id: record.id, status: targetStatus })
      }
      if (response && response.code === 200) {
        // 更新本地状态
        record.status = targetStatus
        message.success('状态更新成功')
      } else {
        message.error('状态更新失败')
        // 如果更新失败，恢复原状态
        record.status = originalStatus
      }
    } catch (e) {
      smartSentry.captureError(e)
      record.status = originalStatus
    } finally {
      record.statusLoading = false
    }
  }

  // -------------- 添加、修改 右侧抽屉 --------------
  const menuOperateModal = ref()

  function showDrawer(rowData) {
    menuOperateModal.value.showDrawer(rowData)
  }

  const selectedUserType = toRef(queryForm, 'userType')

  provide('selectedUserType', selectedUserType)
</script>
